using OrderingSystem.Core.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;

namespace OrderingSystem.Infrastructure.Data
{
    public static class DbInitializer
    {
        public static async Task Initialize(ApplicationDbContext context, ILogger logger = null)
        {
            // 确保数据库已创建
            context.Database.EnsureCreated();
            
            if (logger != null)
            {
                // 验证数据库结构与实体模型的一致性
                var inconsistencies = await DbMigrationHelper.ValidateModelMappings(context, logger);
                
                if (inconsistencies.Count > 0)
                {
                    logger.LogWarning("发现实体映射与数据库结构不一致的问题，请检查实体类的映射配置");
                    foreach (var entity in inconsistencies.Keys)
                    {
                        logger.LogWarning($"实体 {entity} 存在以下问题:");
                        foreach (var issue in inconsistencies[entity])
                        {
                            logger.LogWarning($"  - {issue}");
                        }
                    }
                }
            }

            // 检查是否已有管理员用户
            if (!await context.Admins.AnyAsync(u => u.Username == "abo"))
            {
                // 创建管理员用户
                var adminUser = new Admin
                {
                    Username = "abo",
                    Password = "abo",
                    Role = "管理员",
                    AddTime = DateTime.Now
                };

                context.Admins.Add(adminUser);
                await context.SaveChangesAsync();
            }

            // 检查是否已有普通用户
            if (!await context.Users.AnyAsync(u => u.yonghuming == "admin"))
            {
                // 创建普通用户
                var regularUser = new User
                {
                    yonghuming = "admin",
                    mima = "Admin123!", // 注意：实际应用中应该对密码进行哈希处理
                    xingming = "系统管理员",
                    touxiang = "default.png",
                    addtime = DateTime.UtcNow
                    // Role属性已在数据库映射中被忽略，不需要设置
                };

                context.Users.Add(regularUser);
                await context.SaveChangesAsync();
            }
        }
    }
} 